﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Game.Global
{
    [RequireComponent(typeof(AudioSource))]
    public class SoundManager : MonoBehaviour 
	{
        [SerializeField] AudioClip[] m_BGMs;

        AudioSource m_soundSource;
        AudioSource m_bgmSource;
        int m_currBGMIdx = 0;

        static SoundManager _instance;

        bool isMute = false;
        public static SoundManager instance
        {
            get
            {
                if(_instance==null)
                {
                    throw new System.NullReferenceException("请先设定SoundManager到一个游戏物体上，并指定对应的BGM等内容"); 
                }
                return _instance;
            }
        }

        private void Awake()
        {
            _instance = this;

            //初始化：
            InitSoundPlayer();
        }

        private void InitSoundPlayer()
        {
            var audios = this.GetComponents<AudioSource>();
            
            m_bgmSource = audios[0];
            m_bgmSource.loop = true; //bgm的总是循环播放：


            if (audios.Length > 1)
            {
                m_soundSource = audios[1];
            }

            PlayNextBGM();
        }



        #region Public part

        public void PlaySound(AudioClip clip)
        {
            if(isMute)
            {
                return;
            }

            if (m_soundSource== null )
            {
                throw new System.NullReferenceException("请添加至少两个AudioSource，一个用于播放背景音乐，一个用于播放音效，此播放音效方法才会生效");
            }

            m_soundSource.clip = clip;

            m_soundSource.Play();
        }

        public void PlayNextBGM()
        {
            if (GameObjFunc.IsNullOrEmpty(m_BGMs) || m_BGMs[0] == null)
            {
                return;
            }

            m_bgmSource.clip = m_BGMs[m_currBGMIdx++];
            m_bgmSource.Play();

            if (m_currBGMIdx >= m_BGMs.Length)
            {
                m_currBGMIdx = 0;
            }

        }

        public void StopBGM()
        {
            m_bgmSource.Stop();
        }

        /// <summary>
        /// 打开或者停止音乐
        /// </summary>
        /// <param name="isOn">If set to <c>true</c> turn on.</param>
        public void TurnSoundTo(bool isOn)
        {
            isMute = isOn;
            if(isOn)
            {
                m_bgmSource.Play();
                m_soundSource.Stop();
            }
            else
            {
                m_bgmSource.Stop();
                m_soundSource.Stop();
            }
        }

        #endregion


    }

}